from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session


from info import constants
from info.models import User, News, Category
from info.utils.common import login_user_data
from info.utils.response_code import RET
from . import index_blu
from flask import render_template



@index_blu.route('/')
@login_user_data
def index():
    ##########################以下是用户信息##########################################
    # 因为我们将登陆状态保存在session中，我们是可以获取session数据的
    user_id = session.get('user_id')

    user = None
    if user_id:
        # 如果user_id 有值 说明用户登陆，登陆之后我们查询用户的信息
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # user.to_dict() 可以不调用 to_dict()
    #  直接传对象。 为了让大家适应后边的django 所以我们返回字典
    """
    user.to_dict() if user else None
    if user:
        return user.to_dict()
    else:
        return None
    """

    ##########################以下是排行列表##########################################

    # 1. 根据点击排行获取制定条数的信息

    try:
        click_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # [News,News,News]
    # 将对象列表转换为 字典列表
    # [{},{},{}]
    clicks_news = []
    for item in click_list:
        clicks_news.append(item.to_dict())

    data = {
        'user_info': user.to_dict() if user else None,
        'clicks_news': clicks_news
    }

    return render_template('news/index.html', data=data)



# @index_blu.route('/favicon.ico')
# def favicon():
#     return current_app.send_static_file('news/favicon.ico')
@index_blu.route('/news_list')
def get_index_list():
    #接收参数
    params = request.args
    # 获取参数

    cid = params.get('cid',"1")
    page = params.get('page',1)
    per_page = params.get('per_page',2)

    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 20


    filter = []
    if cid != '1':
        filter.append(News.category_id == cid)

    # 组织查新数据
    try:
        paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page=page, per_page=per_page)
        # 获取当前页的数据
        news = paginate.items
        #总页数
        total_page = paginate.pages
        #　当前页数
        current_page = paginate.page


    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据查询失败")
    #　返回数据

    news_list = []

    for item in news:
        news_list.append(item.to_basic_dict())

    return jsonify(errno=RET.OK,errmsg="ok",
                   news_list=news_list,
                   current_page=current_page,
                   cid=cid,
                   total_page=total_page)
